﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace wd_15_window_status_v1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        // https://blog.csdn.net/wxtcstt/article/details/110385928
        DispatcherTimer timer1 = new DispatcherTimer();
        public MainWindow()
        {
            InitializeComponent();
            timer1.Interval = new TimeSpan(0, 0, 1);
            timer1.Tick += checkMinMinimized;
            //timer1.IsEnabled = true;  //初始化时就启动
        }

        [DllImport("User32.dll", EntryPoint = "ShowWindow")]
        private static extern bool ShowWindow(IntPtr hWnd, int type);

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        //根据父窗口句柄、子窗口句柄、窗口类型、窗口标题 获取句柄
        [DllImport("user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
        private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);


        //获取窗体位置 最小化 最大化 隐藏 api
        [DllImport("User32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
        
        [DllImport("User32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;                             //最左坐标
            public int Top;                             //最上坐标
            public int Right;                           //最右坐标
            public int Bottom;                        //最下坐标
        }

        //static UInt32 SW_HIDE = 0;
        //static UInt32 SW_SHOWNORMAL = 1;
        //static UInt32 SW_NORMAL = 1;
        static UInt32 SW_SHOWMINIMIZED = 2;
        //const UInt32 SW_SHOWMAXIMIZED = 3;
        //static UInt32 SW_MAXIMIZE = 3;
        //static UInt32 SW_SHOWNOACTIVATE = 4;
        //static UInt32 SW_SHOW = 5;
        //static UInt32 SW_MINIMIZE = 6;
        //static UInt32 SW_SHOWMINNOACTIVE = 7;
        //static UInt32 SW_SHOWNA = 8;
        //static UInt32 SW_RESTORE = 9;

        static IntPtr ParenthWnd = new IntPtr(0);

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            timer1.Start();
        }

        //static int old_time1 = 0;
        static int min_state_count = 0;
        static void checkMinMinimized(object sender, EventArgs e)
        {
            //while (true)
            {
                //var proc = Process.GetProcessesByName("Everything.exe");  //invalid name
                var proc = Process.GetProcessesByName("Everything");
                //var proc = Process.GetProcessesByName("Vysor");
                IntPtr LoginWnd = new IntPtr(0);
                LoginWnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Chrome_WidgetWin_1", null);

                if (proc.Length > 0 && 0 < LoginWnd.ToInt32())
                {
                    //bool isMinimized = GetMinimized(LoginWnd);
                    //bool isMinimized = GetMinimized(proc[0].MainWindowHandle);
                    //bool isMinimized = GetMinimized(proc[0].Handle);    // Handle不是主窗口句柄
                    WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
                    placement.length = Marshal.SizeOf(placement);
                    GetWindowPlacement(LoginWnd, ref placement);
                    //if (isMinimized)
                    if(2 == placement.showCmd)
                    {
                        //最小化计数器+1
                        min_state_count++;
                        DateTime now_time1 = DateTime.Now;                        
                        //持续5秒就退出
                        if (min_state_count < 5)
                        {
                            Trace.Write(string.Format("{1} is mini state, {0}\n", now_time1, min_state_count));
                        }
                        else
                        {
                            Trace.Write(string.Format("mini state, ready exit, {0}\n", now_time1));
                            Thread.Sleep(3000);
                        }
                    }
                    else if(1 == placement.showCmd)
                    {
                        RECT rc = new RECT();
                        GetWindowRect(LoginWnd, ref rc);

                        Trace.Write(string.Format("current cmd: {0}\tptMin:{1},{2}\tptMax:{3},{4}\tRC:{5}@@{6}\n",
                            placement.showCmd,
                            placement.ptMinPosition.X,
                            placement.ptMinPosition.Y,
                            placement.ptMaxPosition.X,
                            placement.ptMaxPosition.Y,
                            rc.Left,
                            rc.Right
                            ));  //窗口处于托盘时，MinPos的值不一样。
                        if (double.IsNaN(placement.ptMinPosition.X))
                        {
                            if (double.IsNaN(placement.ptMinPosition.Y))
                            {
                                Trace.Write(string.Format("托盘状态\n"));
                            } 
                            else
                            {
                                Trace.Write(string.Format("正常状态\n"));
                            }
                        } 
                        else
                        {

                        }



                        //最小化计数器-1
                        if(min_state_count-- < 0)
                        {
                            min_state_count = 0;    //最小为0，不能为负数
                        }
                    }
                }
                //Thread.Sleep(1000);
            }
        }

        public static bool GetMinimized(IntPtr handle)
        {
            WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
            placement.length = Marshal.SizeOf(placement);
            GetWindowPlacement(handle, ref placement);
            Trace.Write(string.Format("current cmd: {0}\tptMin:{1},{2}\n",
                placement.showCmd,
                placement.ptMinPosition.X,
                placement.ptMinPosition.Y));  //窗口处于托盘时，MinPos的值不一样。
            return placement.showCmd == SW_SHOWMINIMIZED;
        }

        private struct WINDOWPLACEMENT
        {
            public int length;
            public int flags;
            public int showCmd;
            public Point ptMinPosition; //winform
            public Point ptMaxPosition;
            public Rectangle rcNormalPosition;
        }

        //public static WINDOWPLACEMENT GetShowCmd(IntPtr handle) //封装失败
        //{
        //    WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
        //    placement.length = Marshal.SizeOf(placement);
        //    GetWindowPlacement(handle, ref placement);
        //    Trace.Write(string.Format("current cmd: {0}\tptMin:{1},{2}\n",
        //        placement.showCmd,
        //        placement.ptMinPosition.X,
        //        placement.ptMinPosition.Y));  //窗口处于托盘时，MinPos的值不一样。
        //    return placement;
        //}
    }
}
